<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>事件绑定this</title>
    <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
    <script crossorigin src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
    <style>
        .pl {
           margin-left: 8px;
        }
    </style>
</head>
<body>
<div id="root"></div>
<script type="text/babel">
    const root = ReactDOM.createRoot(document.getElementById('root'))

    class App extends React.Component {
        constructor(props) {
            super();
            this.state = {
                message: undefined,
                bindMethods: [
                    '1.默认绑定，方法独立调用 foo()',
                    '2.隐式绑定，被一个对象调用 obj.foo() -> foo',
                    '3.显示绑定，call/apply/bind foo.call("abc") -> String("abc")',
                    '4.new绑定，']
            }
            // 1.绑定方式1 bind绑定
            this.click1 = this.click1.bind(this);
        }

        click1 = function () {
            this.setState({
                message: "click 1!"
            })
        };

        // 2.绑定方式2 箭头函数绑定
        click2 = () => {
            this.setState({
                message: "click 2!"
            })
        };

        click3 = function () {
            this.setState({
                message: "click 3!"
            })
        };

        render() {
            const {message, bindMethods} = this.state
            return (
                <div>
                    <h1>事件绑定this</h1>
                    <div>点击了 {message}</div>
                    <div>
                        <button onClick={this.click1}>click1</button>
                        <button className='pl' onClick={this.click2}>click2</button>
                        {/* 3.绑定方式3 箭头函数绑定 */}
                        <button className='pl' onClick={() => this.click3()}>click3</button>
                    </div>
                    <h1>this绑定规则</h1>
                    <ul>
                        {bindMethods.map((method, i) => <li key={i}>{method}</li>)}
                    </ul>
                </div>
            );
        }
    }
    root.render(<App />);

    const obj = {
        foo: function () {
            console.log('foo: ', this)
        },
    }
    const conf = {
        cli: obj.foo
    }

    const fun = conf.foo
    fun() // 此时为默认绑定
</script>
</body>
</html>